import subprocess
import shlex
import re
import json
import logging 
LOGGER = logging.getLogger("AUTO")
FORMAT = '%(asctime)s %(message)s'   # 设置Logger的格式                                                                                                                       
logging.basicConfig(format=FORMAT)       # 设置Logger的格式                                                                                                       
LOGGER.setLevel(logging.DEBUG)

def distribute(dists = ['MANJARO','Ubuntu']):
    """
    获取发行版信息
    """
    p = subprocess.Popen(shlex.split("uname -a"),stdout=subprocess.PIPE)
    info = re.findall("|".join(dists),p.stdout.read().decode("utf-8"))
    return info[0] if len(info)>0 else None

def install_lists(filename):
    """
    配置文件解析
    """
    with open(filename,'r') as f:
        info = json.load(f)
    return info

def check_installed(softs):
    """
    过滤并生成当前系统没有安装的软件包
    """
    not_installed = []
    for s in softs:
        args = shlex.split("which {}".format(s))
        LOGGER.info("Software = {} ".format(s))
        p = subprocess.Popen(args,stdout=subprocess.PIPE)
        out = p.stdout.read().decode("utf-8")
        if len(out)==0 or out == " ":
            not_installed.append(s)
    LOGGER.debug("Install list = {} execution list = {}".format(softs,not_installed))
    return not_installed

def install_software_with_os(softwares,dist):
    """
    根据OS发行版安装对应的软件
    """
    softwares = check_installed(softwares)
    if len(softwares) == 0:
        return []
    if dist.lower() == 'manjaro':
        command = "sudo pacman -S {}".format(" ".join(softwares))
        args = shlex.split(command)
    elif dist.lower() == 'ubuntu':
        command = "sudo apt install {} -y".format(" ".join(softwares))
        args = shlex.split(command)
    else:
        pass
    return args

def install_software(software,dist):
    assert '{}_lists'.format(dist.lower()) in software,"{} must be in {}".format(install_lists,software.keys())
    s_list = software['{}_lists'.format(dist.lower())]
    command = install_software_with_os(s_list,dist)    
    if len(command)>0:
        p = subprocess.Popen(command,stdout=subprocess.PIPE)
        output = p.stdout.read().decode("utf-8")
    

if __name__ == "__main__":
    info = install_lists('config.json')
    dist = distribute()
    mesg = install_software(info,dist)
